using SqlSugar;
using WinformDevFramework.Core.Winform;
using WinformDevFramework.IServices;
using WinformDevFramework;
using WinformDevFramework.IServices.System;
using WinformDevFramework.Services;

namespace WinformDevFramework
{
    public partial class Frmw_Payment : BaseForm1
    {
        private Iw_PaymentServices _w_PaymentServices;
        private IsysDicDataServices _sysDicDataServices;
        private Iw_SupplierServices _w_SupplierServices;
        private Iw_SettlementAccountServices _w_SettlementAccountServices;
        private Iw_BuyServices _wBuyServices;
        private Iw_PaymentDetailServices _wPaymentDetailServices;
        private ISysUserServices _wSysUserServices;
        public Frmw_Payment(Iw_PaymentServices w_PaymentServices, IsysDicDataServices sysDicDataServices, Iw_SupplierServices w_SupplierServices, Iw_SettlementAccountServices w_SettlementAccountServices, Iw_BuyServices wBuyServices, Iw_PaymentDetailServices wPaymentDetailServices,ISysUserServices sysUserServices)
        {
            _w_PaymentServices = w_PaymentServices;
            InitializeComponent();
            _sysDicDataServices = sysDicDataServices;
            _w_SupplierServices = w_SupplierServices;
            _w_SettlementAccountServices = w_SettlementAccountServices;
            _wBuyServices = wBuyServices;
            _wPaymentDetailServices = wPaymentDetailServices;
            _wSysUserServices = sysUserServices;
        }

        public override void Init()
        {
            base.Init();
            //查询数据
            this.dataGridViewList.DataSource = GetData();

            // 设置隐藏列
            this.dataGridViewList.Columns["PayCode"].HeaderText = "付款单号";
            this.dataGridViewList.Columns["SupplierCode"].HeaderText = "供应商编码";
            this.dataGridViewList.Columns["SupplierName"].HeaderText = "供应商名称";
            this.dataGridViewList.Columns["PayDate"].HeaderText = "付款时间";
            this.dataGridViewList.Columns["MakeUserID"].Visible = false;
            this.dataGridViewList.Columns["SettlementType"].HeaderText = "结算方式";
            this.dataGridViewList.Columns["SettlementCode"].HeaderText = "结算账户";
            this.dataGridViewList.Columns["SettlementName"].HeaderText = "结算账户名称";
            this.dataGridViewList.Columns["TotalPrice"].HeaderText = "付款金额";
            this.dataGridViewList.Columns["Remark"].HeaderText = "备注";

            //设置结算方式
            SettlementType.DataSource = _sysDicDataServices.QueryListByClause(p => p.DicTypeID == 2004);
            SettlementType.DisplayMember = "DicData";
            SettlementType.ValueMember = "ID";

            //设置供应商
            var customers = _w_SupplierServices.Query();
            SupplierName.DataSource = customers;
            SupplierName.DisplayMember = "SupplierName";
            SupplierName.ValueMember = "SupplierCode";
            SupplierName.SelectedIndexChanged += SupplierName_SelectedIndexChanged; ;

            //设置 结算账户
            var settlementAccount = _w_SettlementAccountServices.Query();
            SettlementName.DataSource = settlementAccount;
            SettlementName.DisplayMember = "Name";
            SettlementName.ValueMember = "Code";
            //设置制单人
            MakeUserID.DataSource = _wSysUserServices.Query();
            MakeUserID.DisplayMember = "Fullname";
            MakeUserID.ValueMember = "ID";
            SettlementName.SelectedIndexChanged += SettlementName_SelectedIndexChanged; ;
            SetToolButtonStatus(formStatus);
            SetToolsButton();
        }

        private void SupplierName_SelectedIndexChanged(object? sender, EventArgs e)
        {
            SupplierCode.Text = SupplierName.SelectedValue.ToString();
            SetDetailBuy();
        }

        private void SettlementName_SelectedIndexChanged(object? sender, EventArgs e)
        {
            SettlementCode.Text = SettlementName.SelectedValue.ToString();
        }

        public override void TabControlSelectingFunction(object? sender, TabControlCancelEventArgs e)
        {
            base.TabControlSelectingFunction(sender, e);
        }

        public override void DataGridViewListDoubleClick(object? sender, DataGridViewCellEventArgs e)
        {
            base.DataGridViewListDoubleClick(sender, e);
            var g = (DataGridView)sender;
            var model = g.CurrentRow.DataBoundItem as w_Payment;

            //给详情页设置数据
            this.txtID.Text = model.ID.ToString();
            this.PayCode.Text = model.PayCode;
            this.SupplierCode.Text = model.SupplierCode;
            this.SupplierName.Text = model.SupplierName;
            this.PayDate.Text = model.PayDate.ToString();
            this.MakeUserID.SelectedValue = model.MakeUserID;
            this.SettlementType.Text = model.SettlementType;
            this.SettlementCode.Text = model.SettlementCode;
            this.SettlementName.Text = model.SettlementName;
            this.TotalPrice.Text = model.TotalPrice.ToString();
            this.Remark.Text = model.Remark;
            SetDetailBuy();
            SetDataToDetail(GetDetailData(model.PayCode));
            SetToolButtonStatus(formStatus);
        }

        public override void AddFunction(object sender, EventArgs e)
        {
            base.AddFunction(sender, e);
            SetToolButtonStatus(formStatus);
            //设置供应商
            var suppliers = _w_SupplierServices.Query();
            SupplierCode.Text = suppliers.First().SupplierCode;

            //设置 结算账户
            var settlementAccount = _w_SettlementAccountServices.Query();
            SettlementCode.Text = settlementAccount.First().Code;

            MakeUserID.SelectedValue = AppInfo.User.ID;
            SetDetailBuy();
            dataGridViewDetail.Rows.Clear();
            SetDataGridViewReadonlyStatus();
        }

        public override void EditFunction(object sender, EventArgs e)
        {
            base.EditFunction(sender, e);
            SetToolButtonStatus(formStatus);
        }

        public override void SaveFunction(object sender, EventArgs e)
        {
            base.SaveFunction(sender, e);
            {
                //新增
                if (string.IsNullOrEmpty(txtID.Text))
                {
                    w_Payment model = new w_Payment();
                    // TODO获取界面的数据
                    if (string.IsNullOrEmpty(this.PayCode.Text))
                    {
                        model.PayCode = $"FK{DateTime.Now.ToString("yyyyMMddHHmmss")}";
                    }
                    else
                    {
                        model.PayCode = this.PayCode.Text;
                    }
                    model.SupplierCode = this.SupplierCode.Text;
                    model.SupplierName = this.SupplierName.Text;
                    model.PayDate = this.PayDate.Value;
                    model.MakeUserID = this.MakeUserID.SelectedValue.ToInt32();
                    model.SettlementType = this.SettlementType.Text;
                    model.SettlementCode = this.SettlementCode.Text;
                    model.SettlementName = this.SettlementName.Text;
                    model.TotalPrice = this.TotalPrice.Text.ToDecimal();
                    model.Remark = this.Remark.Text;

                    List<w_PaymentDetail> details = new List<w_PaymentDetail>();
                    foreach (DataGridViewRow row in dataGridViewDetail.Rows)
                    {
                        if (!row.IsNewRow)
                        {
                            w_PaymentDetail detail = new w_PaymentDetail();
                            detail.BuyCode = row.Cells["BuyCode"].FormattedValue.ToString();
                            detail.Amount1 = row.Cells["Amount1"].FormattedValue.ToDecimal();
                            detail.Amount2 = row.Cells["Amount2"].FormattedValue.ToDecimal();
                            detail.Amount3 = row.Cells["Amount3"].FormattedValue.ToDecimal();
                            detail.Amount4 = row.Cells["Amount4"].FormattedValue.ToDecimal();
                            detail.Remark = row.Cells["RemarkD"].FormattedValue.ToString();
                            details.Add(detail);
                        }
                    }
                    var id = _w_PaymentServices.AddPaymentInfo(model, details);
                    if (id > 0)
                    {
                        MessageBox.Show("保存成功！", "提示");
                        txtID.Text = id.ToString();
                        PayCode.Text = model.PayCode;
                        SetDataToDetail(GetDetailData(model.PayCode));
                    }
                }
                // 修改
                else
                {
                    w_Payment model = _w_PaymentServices.QueryById(int.Parse(txtID.Text));
                    // TODO获取界面的数据
                    model.PayCode = this.PayCode.Text;
                    model.SupplierCode = this.SupplierCode.Text;
                    model.SupplierName = this.SupplierName.Text;
                    model.PayDate = this.PayDate.Value;
                    model.MakeUserID = this.MakeUserID.SelectedValue.ToInt32();
                    model.SettlementType = this.SettlementType.Text;
                    model.SettlementCode = this.SettlementCode.Text;
                    model.SettlementName = this.SettlementName.Text;
                    model.TotalPrice = this.TotalPrice.Text.ToDecimal();
                    model.Remark = this.Remark.Text;
                    List<w_PaymentDetail> details = new List<w_PaymentDetail>();
                    foreach (DataGridViewRow row in dataGridViewDetail.Rows)
                    {
                        if (!row.IsNewRow)
                        {
                            w_PaymentDetail detail = new w_PaymentDetail();
                            detail.BuyCode = row.Cells["BuyCode"].FormattedValue.ToString();
                            detail.PayCode = row.Cells["PayCodeD"].FormattedValue.ToString();
                            detail.PayDetailCode = row.Cells["PayDetailCode"].FormattedValue.ToString();
                            detail.Amount1 = row.Cells["Amount1"].FormattedValue.ToDecimal();
                            detail.Amount2 = row.Cells["Amount2"].FormattedValue.ToDecimal();
                            detail.Amount3 = row.Cells["Amount3"].FormattedValue.ToDecimal();
                            detail.Amount4 = row.Cells["Amount4"].FormattedValue.ToDecimal();
                            detail.Remark = row.Cells["RemarkD"].FormattedValue.ToString();
                            details.Add(detail);
                        }
                    }
                    if (_w_PaymentServices.UpdatePaymentInfo(model, details))
                    {
                        MessageBox.Show("保存成功！", "提示");
                        SetDataToDetail(GetDetailData(model.PayCode));
                    }
                }
                SetToolButtonStatus(formStatus);
                //列表重新赋值
                this.dataGridViewList.DataSource = GetData();
                //SetDataToDetail(GetDetailData());
            }
        }

        public override void CanelFunction(object sender, EventArgs e)
        {
            bool isAdd = formStatus == FormStatus.Add;
            base.CanelFunction(sender, e);
            SetToolButtonStatus(formStatus);
            btnEdit.Enabled = !isAdd;
            btnDel.Enabled = !isAdd;
            ClearControlsText(this.groupBox1);
            dataGridViewDetail.Rows.Clear();
        }

        public override void DelFunction(object sender, EventArgs e)
        {
            base.DelFunction(sender, e);
            var result = MessageBox.Show("是否删除？", "确认", MessageBoxButtons.YesNoCancel);
            if (result == DialogResult.Yes)
            {
                if (_w_PaymentServices.DeletePaymentInfo(new w_Payment()
                {
                    ID = txtID.Text.ToInt32(),
                    PayCode = PayCode.Text
                }))
                    formStatus = FormStatus.Del;
                SetToolButtonStatus(formStatus);
                //列表重新赋值
                dataGridViewDetail.Rows.Clear();
                this.dataGridViewList.DataSource = GetData();
            }
        }

        public override void SetToolButtonStatus(FormStatus status)
        {
            base.SetToolButtonStatus(status);
            switch (status)
            {
                case FormStatus.Add:
                    {
                        btnAdd.Enabled = false;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = true;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = true;
                        dataGridViewDetail.ReadOnly = false;
                        SetControlStatus(this.groupBox1, true);
                        ClearControlsText(this.groupBox1);
                        break;
                    }
                case FormStatus.Edit:
                    {
                        btnAdd.Enabled = false;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = true;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = true;
                        dataGridViewDetail.ReadOnly = false;
                        SetControlStatus(this.groupBox1, true);
                        break;
                    }
                case FormStatus.View:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = true;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Canel:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.First:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Save:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = true;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Del:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        ClearControlsText(this.groupBox1);
                        break;
                    }
            }
        }

        public override bool ValidateData()
        {
            return true;
        }
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <returns></returns>
        private List<w_Payment> GetData()
        {
            List<w_Payment> data = new List<w_Payment>();
            data = _w_PaymentServices.Query();
            return data;
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 设置明细采购单下拉
        /// </summary>
        /// 
        private void SetDetailBuy()
        {
            //设置 明细表中销售单号 获取该客户下未结清销售订单
            BuyCode.DataSource = _wBuyServices.QueryListByClause(p => p.SupplierCode.Equals(SupplierCode.Text));
            BuyCode.ValueMember = "BuyCode";
            BuyCode.DisplayMember = "BuyCode";
        }

        private void dataGridViewDetail_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                if (dataGridViewDetail.Columns[e.ColumnIndex].Name == "BuyCode" && dataGridViewDetail.Rows[e.RowIndex].Cells["BuyCode"].Value != null)
                {
                    string code = dataGridViewDetail.Rows[e.RowIndex].Cells["BuyCode"].Value.ToString();
                    var sale = _wBuyServices.QueryByClause(p =>
                        p.BuyCode == code);
                    if (sale != null)
                    {
                        dataGridViewDetail.Rows[e.RowIndex].Cells["Amount1"].Value = sale.TotalPrice;
                        dataGridViewDetail.Rows[e.RowIndex].Cells["Amount2"].Value = sale.TotalPrice1;
                        dataGridViewDetail.Rows[e.RowIndex].Cells["Amount3"].Value = sale.TotalPrice2;

                    }
                }

                //汇总
                if (dataGridViewDetail.Columns[e.ColumnIndex].Name == "Amount4")
                {
                    SetFormTotalData();
                }
            }
        }
        private void SetFormTotalData()
        {
            decimal total = 0;
            foreach (DataGridViewRow row in dataGridViewDetail.Rows)
            {
                if (!row.IsNewRow)
                {
                    total += row.Cells["Amount4"] == null ? 0 : row.Cells["Amount4"].Value.ToDecimal();
                }
            }
            TotalPrice.Text = total.ToString();
        }

        /// <summary>
        /// 获取明细数据
        /// </summary>
        /// <returns></returns>
        private List<w_PaymentDetail> GetDetailData(string code)
        {
            List<w_PaymentDetail> data = new List<w_PaymentDetail>();
            data = _wPaymentDetailServices.QueryListByClause(p => p.PayCode == code);
            return data;
        }

        /// <summary>
        /// 明细表 设置数据
        /// </summary>
        /// <param name="details"></param>
        private void SetDataToDetail(List<w_PaymentDetail> details)
        {
            dataGridViewDetail.Rows.Clear();
            details.ForEach(p =>
            {
                dataGridViewDetail.Rows.AddCopy(dataGridViewDetail.Rows.Count - 1);
                DataGridViewRow row = dataGridViewDetail.Rows[dataGridViewDetail.Rows.Count - 2];
                row.Cells["PayCodeD"].Value = p.PayCode;
                row.Cells["PayDetailCode"].Value = p.PayDetailCode;
                row.Cells["BuyCode"].Value = p.BuyCode;
                row.Cells["Amount1"].Value = p.Amount1;
                row.Cells["Amount2"].Value = p.Amount2;
                row.Cells["Amount3"].Value = p.Amount3;
                row.Cells["Amount4"].Value = p.Amount4;
                row.Cells["RemarkD"].Value = p.Remark;
            });
        }
        private void SetDataGridViewReadonlyStatus()
        {
            dataGridViewDetail.ReadOnly = false;
            string[] cols = { "BuyCode", "Amount4", "RemarkD" };
            foreach (DataGridViewColumn column in dataGridViewDetail.Columns)
            {
                if (!cols.Contains(column.Name))
                {
                    column.ReadOnly = true;
                }
            }
        }
    }
}
